package com.dabai.sas.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.dabai.sas.R;
import com.dabai.sas.databinding.ActivityMusicPlayerBinding;
import com.dabai.sas.utils.DabaiUtils;
import com.dabai.sas.utils.FileUtil;
import com.dabai.sas.utils.UriUtils;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Timer;

public class MusicPlayerActivity extends AppCompatActivity {

    Context context;
    String TAG = "DABAI";
    Uri uri;

    ActivityMusicPlayerBinding activityMusicPlayerBinding;
    MediaPlayer mp;

    AudioManager audioManager;

    private boolean isSeekBarChanging;//互斥变量，防止进度条与定时器冲突。

    SimpleDateFormat format;

    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        activityMusicPlayerBinding = ActivityMusicPlayerBinding.inflate(getLayoutInflater());
        setContentView(activityMusicPlayerBinding.getRoot());

        context = getApplicationContext();

        this.setFinishOnTouchOutside(false);

        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DabaiUtils.showToast(context, "请点击申请'储存权限'!");
            startActivity(new Intent(this, PermissionsActivity.class));
            finish();
            return;
        }

        mp = new MediaPlayer();

        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        format = new SimpleDateFormat("mm:ss");

        activityMusicPlayerBinding.play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playOrPause();
            }
        });
        activityMusicPlayerBinding.close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stop();
                finish();
            }
        });

       activityMusicPlayerBinding.seekBar.setOnSeekBarChangeListener(new MySeekBar());

        try {
            init();
        } catch (Exception e) {
            DabaiUtils.showToast(this,"音频播放失败!");
            Log.d(TAG, "onCreate: "+e);
            finish();
        }

    }

    private void init() throws IOException {

        //拿到uri
        uri = getIntent().getData();

        if (uri.toString().startsWith("file:///")) {
            File file = new File(FileUtil.getFileAbsolutePath(this, uri));
            activityMusicPlayerBinding.textView1.setText(file.getName());
        } else {
            UriUtils file = new UriUtils(context, uri);
            activityMusicPlayerBinding.textView1.setText(file.getFileName());
        }
        mp.setDataSource(context,uri);
        mp.prepare();


        activityMusicPlayerBinding.seekBar.setProgress(mp.getCurrentPosition());
        activityMusicPlayerBinding.seekBar.setMax(mp.getDuration());

        playOrPause();


    }


    /**
     * 刷新 进度
     */
    private final Runnable task = new Runnable() {

        @SuppressLint("SetTextI18n")
        public void run() {
            if (mp != null) {

                if (!mp.isPlaying()){
                    activityMusicPlayerBinding.play.setText("播放");
                    mMusicHandler.removeCallbacks(task);
                    return;
                }

                mMusicHandler.postDelayed(task, 100);

                if (!isSeekBarChanging) {
                    activityMusicPlayerBinding.seekBar.setProgress(mp.getCurrentPosition());
                    activityMusicPlayerBinding.textView2.setText(format.format(mp.getCurrentPosition()) + "/"+format.format(mp.getDuration()));
                }
            }
        }
    };


    private final Handler mMusicHandler = new Handler();

    public void playOrPause() {
        if(mp.isPlaying()){
            activityMusicPlayerBinding.play.setText("播放");
            mp.pause();
            mMusicHandler.removeCallbacks(task);
        } else {
            activityMusicPlayerBinding.play.setText("暂停");
            mp.start();
            mMusicHandler.post(task);
        }
    }
    public void stop() {
        if (mp != null) {
            mp.stop();
            try {
                mp.prepare();
                mp.seekTo(0);
                mp.release();
                mp = null;
                mMusicHandler.removeCallbacks(task);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stop();
    }

    /*进度条处理*/
    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        @SuppressLint("SetTextI18n")
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            activityMusicPlayerBinding.textView2.setText(format.format(progress) + "/"+format.format(mp.getDuration()));
        }

        /*滚动时,应当暂停后台定时器*/
        public void onStartTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = true;
        }

        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarChanging = false;
            mp.seekTo(seekBar.getProgress());
        }
    }
}